package org.mzx.shortLink.adminn.common.Interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.mzx.shortLink.adminn.common.ThreadLocal.threadlocal;
import org.mzx.shortLink.adminn.common.ThreadLocal.threadlocalDTO;
import org.mzx.shortLink.adminn.domain.entity.TUser;
import org.mzx.shortLink.starter.convention.Exception.ClientException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static org.mzx.shortLink.adminn.common.enums.redisEnum.LOGIN_KEY;

@Component
@RequiredArgsConstructor
public class loginInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从前端的请求头中获取到用户id和token
        //String requestURI = request.getRequestURI();
        String token = request.getHeader("token");
        String username = request.getHeader("username");
        if(StrUtil.isBlank(token)||StrUtil.isBlank(username)) {
            return true;
           // throw new ClientException("该用户未登录");
        }
        String  JsonvalueStr = (String)redisTemplate.opsForHash().get(LOGIN_KEY + username, "value");
        if(StrUtil.isBlank(JsonvalueStr)) {
            return false;
        }
        TUser user = JSONUtil.toBean(JsonvalueStr, TUser.class);
        threadlocal.setLoginUser(threadlocalDTO.builder()
                        .token(token)
                        .username(username)
                        .phone(user.getPhone())
                        .build());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadlocal.clear();
    }
}
